<?php

require(ROOT . '/controllers/CommonController.class.php');

class FtpServerController extends CommonController {

	public function __construct() {
		parent::__construct(__CLASS__);

		$this->db = DB::open('reading');
	}

	public function indexAction() {
		$sql = "SELECT * FROM ftp_server";

		$records = $this->db->query($sql);

		$this->assign('records', $records);

		$this->rend('index');
	}

	public function newAction() {
		$this->rend('new');
	}

	public function insertAction() {
		$data = array(
			'name' => requestPost('name'),
			'host' => requestPost('host'),
			'port' => requestPost('port'),
			'username' => requestPost('username'),
			'password' => requestPost('password'),
			'created_at' => time()
		);

		$model = new Model('ftp_server', $this->db);

		if ($model->insert($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('ftp_server/index'));
	}

	public function editAction($segments) {
		$id = (int) $segments[0];

		$sql = "SELECT * FROM ftp_server WHERE id={$id}";

		$records = $this->db->query($sql);

		$this->assign('record', $records[0]);

		$this->rend('edit');
	}

	public function updateAction() {
		$data = array(
			'id' => requestPost('id'),
			'name' => requestPost('name'),
			'host' => requestPost('host'),
			'port' => requestPost('port'),
			'username' => requestPost('username'),
			'password' => requestPost('password'),
		);

		$model = new Model('ftp_server', $this->db);

		if ($model->update($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('ftp_server/index'));
	}

	public function deleteAction($segments) {
		$id = (int) $segments[0];

		$sql = "delete from ftp_server where id={$id}";

		if ($this->db->exec($sql)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('ftp_server/index'));
	}

}
